package ejemplo;

import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;

public class Select extends HttpServlet {

  private AccesoDatos ad;
  private ResultSet rs;
  private MyTableModel mtb;
  private String table, mensaje;
  private String isbn, titulo, autor, precio, idtema, tema;

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {} 

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {} 

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    RequestDispatcher rd;
    HttpSession session=request.getSession();
    ServletContext context = getServletContext();
    InputStream header = context.getResourceAsStream("/header.xhtml");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if(request.getParameter("referer") != null){ // si no es nulo, es "search"       
       mensaje = "";
       table=request.getParameter("table");
       session.setAttribute("table",table);
       isbn=request.getParameter("isbn");
       session.setAttribute("isbn",isbn);
       titulo=request.getParameter("titulo");
       session.setAttribute("titulo",titulo);
       autor=request.getParameter("autor");
       session.setAttribute("autor",autor);
       precio=request.getParameter("precio");
       session.setAttribute("precio",precio);
       idtema=request.getParameter("idtema");
       session.setAttribute("idtema",idtema);
       tema=request.getParameter("tema");
       session.setAttribute("tema",tema);
    }
    else{
       mensaje=(String)request.getAttribute("mensaje");
       table=(String)session.getAttribute("table");
       isbn=(String)session.getAttribute("isbn");
       titulo=(String)session.getAttribute("titulo");
       autor=(String)session.getAttribute("autor");
       precio=(String)session.getAttribute("precio");
       idtema=(String)session.getAttribute("idtema");
       tema=(String)session.getAttribute("tema");
    }

    try {
       if (header != null) {
         InputStreamReader isr = new InputStreamReader(header);
         BufferedReader reader = new BufferedReader(isr);
         String line ="";
         if(table.equals("libros")){
            while ((line = reader.readLine()) != null){
              if(Pattern.matches(".*OPER.*", line))
                out.print(line.replaceFirst("OPER", "Listado de libros"));
              else out.print(line);
            }
         } //endif table == libros
         else if(table.equals("temas")){
            while ((line = reader.readLine()) != null){
              if(Pattern.matches(".*OPER.*", line))
                out.print(line.replaceFirst("OPER", "Listado de temas"));
              else out.print(line);
            }
         } //endif table == temas
       } //endif if (header != null)

       ad = new AccesoDatos("gencod");

       if(table.equals("libros")){
      
          rs = ad.getLibros(isbn, titulo, autor, precio, idtema);  
          
          mtb = new MyTableModel(rs);
         out.println("<br/>");
         out.println("<table width=100% border=0 cellpadding=0 cellspacing=0>");
         // imprimir encabezado de la consulta
         out.println("<tr>");
         for (int col = 0; col < mtb.getColumnCount(); col++){
           if(col % 2 == 0)
              out.println("<td bgcolor=\"#93BEE2\">&nbsp;<font class=\"sb\">");
           if(col % 2 == 1)
              out.println("<td bgcolor=\"#336699\">&nbsp;<font class=\"sw\" color=\"#ffffff\">");
           out.println("<b>" + mtb.getColumnName(col) + "</b>");
           out.println("</font></td>");
         }
         out.println("<td bgcolor=\"#93BEE2\" width=\"2%\"></td>");
         out.println("</tr>");

         //imprimir cuerpo de la consulta
         for (int row = 0; row < mtb.getRowCount(); row++){
            out.println("<tr bgcolor=\"#FFFFFF\">");
            for (int col = 0; col < mtb.getColumnCount(); col++){
               out.println("<td>&nbsp;<font class=s>");
               if(col == 1)
                  out.println("<a href=modify?table=libros&isbn=" + mtb.getValueAt(row, 0) +" color=\"#000000\">");
               out.println(mtb.getValueAt(row, col));
               out.println("</font></td>");
            }

            out.println("<td bgcolor=\"#336699\">");
            out.println("<form Method=POST action=./confirm>");
            out.println("<input type=Hidden name=table value=\"libros\"/>");
            out.println("<input type=Hidden name=isbn value=\"" + mtb.getValueAt(row, 0) +"\"/>");
            out.println("<input TYPE=submit VALUE=Borrar>");
            out.println("</form>");
            out.println("</td>");
            out.println("</tr>");
         }

         out.println("<tr bgcolor=\"#336699\">");
         out.println("<td colspan=5 VALIGN=TOP style=padding-left:5px;border:none>");
         out.println("<font face=Lucida Sans color=#ffffff><font size=+1>");
         out.println("<b>Total: " + mtb.getRowCount() + " libros encontrados</b></font></font></td>");
       
         out.println("<td><form Method=POST action=./add>");
         out.println("<input type=Hidden name=referer value=\"select\"/>");
         out.println("<input type=Hidden name=table value=\"libros\">");
         out.println("<input TYPE=submit VALUE=Agregar></form></td>");
         out.println("</tr>"); 
         
         out.println("<tr bgcolor=\"#93BEE2\">");
         out.println("<td colspan=\"1\" align=\"left\">");
         out.println("<form Method=Post action=\"./search\">");
         out.println("<input type=Hidden name=table value=\"libros\">");
         out.println("<input TYPE=submit VALUE=\"Volver\"/>");
         out.println("</form>");
         out.println("</td>");
         out.println("<td colspan=\"3\" align=\"center\">");
         out.println("<form Method=Post action=\"./menu\">");
         out.println("<input TYPE=submit VALUE=\"Inicio\"/>");
         out.println("</form>");
         out.println("</td>");
         
         out.println("<td colspan=\"2\" align=\"right\">");
         out.println("<form Method=Post action=\"./index\">");
         out.println("<input TYPE=submit VALUE=\"Salir\"/>");
         out.println("</form>");
         out.println("</td>");
         out.println("</tr>");                  
         out.println("</table>");
       } //endif table == libros
       else if(table.equals("temas")){
     //    tema=request.getParameter("tema");
         rs = ad.getTemas(tema);
         mtb = new MyTableModel(rs);

         out.println("<br/><center>");
         out.println("<table width=30% border=0 cellpadding=0 cellspacing=0>");
         // imprimir encabezado de la consulta
         out.println("<tr>");
         out.println("<td colspan=\"3\" bgcolor=\"#336699\">");
         out.println("<font class=\"sw\" color=\"#ffffff\">");
         out.println("<b>&nbsp;" + mtb.getColumnName(1) + "</b></font></td>");
         out.println("</tr>");

         //imprimir cuerpo de la consulta
         for (int row = 0; row < mtb.getRowCount(); row++){
            out.println("<tr bgcolor=\"#FFFFFF\">");
            out.println("<td colspan=\"2\"><font class=s>");
            out.println("<a href=modify?table=temas&id=" + mtb.getValueAt(row, 0) +" color=\"#000000\">");
            out.println("&nbsp;" + mtb.getValueAt(row, 1));
            out.println("</font></td>");

            out.println("<td align=\"center\" bgcolor=\"#336699\">");
            out.println("<form Method=POST action=./confirm>");
            out.println("<input type=Hidden name=table value=\"temas\"/>");
            out.println("<input type=Hidden name=id value=\"" + mtb.getValueAt(row, 0) +"\"/>");
            out.println("<input TYPE=submit VALUE=Borrar>");
            out.println("</form>");
            out.println("</td>");

            out.println("</tr>");
         }

         out.println("<tr bgcolor=\"#336699\">");
         out.println("<td colspan=\"2\">");
         out.println("<font face=Lucida Sans color=#ffffff><font size=+1>");
         out.println("<b>Total: " + mtb.getRowCount() + " temas encontrados</b></font></font></td>");

         out.println("<td align=\"center\"><form Method=POST action=./add>");
         out.println("<input type=Hidden name=referer value=\"select\"/>");
         out.println("<input type=Hidden name=table value=\"temas\">");
         out.println("<input TYPE=submit VALUE=Agregar></form></td>");

         out.println("</tr>");
         out.println("<tr bgcolor=\"#93BEE2\">");
         out.println("<td align=\"left\">");
         out.println("<form Method=Post action=\"./search\">");
         out.println("<input type=Hidden name=table value=\"temas\">");
         out.println("<input TYPE=submit VALUE=\"Volver\"/>");
         out.println("</form>");
         out.println("</td>");

         out.println("<td align=\"left\">");
         out.println("<form Method=Post action=\"./menu\">");
         out.println("<input TYPE=submit VALUE=\"Inicio\"/>");
         out.println("</form>");
         out.println("</td>");

         out.println("<td align=\"right\">");
         out.println("<form Method=Post action=\"./index\">");
         out.println("<input TYPE=submit VALUE=\"Salir\"/>");
         out.println("</form>");
         out.println("</td>");
         out.println("</tr>");
         out.println("</table></center>");

       }//endif table == temas
       if(mensaje != null){
         out.println("<center><h2>");
         out.println("<font color=\"#FFFFFF\">");
         out.println(mensaje);
         out.println("</font></h2></center>");
       }
    } catch(ClassNotFoundException cnfe){
      rd=request.getRequestDispatcher("/index");
      mensaje="Error fatal. Excepcion de clase no encontrada: " + cnfe.getMessage();
      request.setAttribute("mensaje",mensaje);
      rd.forward(request,response);
    } catch(SQLException sqle){
      rd=request.getRequestDispatcher("/index");
      mensaje="Error fatal. Excepcion de SQL: " + sqle.getErrorCode();
      request.setAttribute("mensaje",mensaje);
      rd.forward(request,response);
    }
    finally {   out.close();   }
  }

  @Override
  public String getServletInfo(){ return "Short description"; }
}